<template>
  <div class="pay-container">
      <!-- 生成微信支付二维码 -->
    <div class="erwei">
        <img :src="payUrl" alt="">
    </div>
    <span>请使用微信进行支付</span>
      <el-descriptions title="订单详情">
        <el-descriptions-item label="订单号">{{orderDetail.create_time}}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{orderDetail.create_time}}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{orderDetail.orderDetail[0].productName}}</el-descriptions-item>
        <el-descriptions-item label="商品描述">{{orderDetail.orderDetail[0].description}}</el-descriptions-item>
        <el-descriptions-item label="商品数量">{{orderDetail.orderDetail[0].quantity}}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{orderDetail.user_nickname}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{orderDetail.user_phone?orderDetail.user_phone:"没有手机号"}}</el-descriptions-item>
        <el-descriptions-item label="总价">
            {{orderDetail.total_fee}}
        </el-descriptions-item>
    </el-descriptions>
  </div>
</template>
<script>
import { mapState } from "vuex"
import * as api from "../../../api/index"
import qrcode from 'qrcode'
export default {
    data(){
        return{
            orderDetail:{
                orderDetail:[{
                    productName:"",
                    description:"",
                    quantity:""
                }]
            },
            payUrlres:{},
            payUrl:""
        }
    },
  computed: {
    ...mapState(["order_id"]),
  },
  created() {
    if (!this.order_id) {
      this.$alert("本次交易已取消，请重新提交", "提示", {
        confirmButtonText: "确定",
        callback: action => {
          this.$router.push({name:'pre_order'})
        }
      })
      return
    }
    Promise.all([api.getOrderdetail(this.order_id),api.commitOrder(this.order_id)])
    .then(res=>{
        let orderDetail = res[0].data.data
        let payUrlres = res[1].data
        this.orderDetail = orderDetail;
        console.log(this.orderDetail);
        // this.payUrlres = payUrlres

        qrcode.toDataURL(payUrlres.code_url, (err,dataUrl)=>{
            this.payUrl = dataUrl//生成二维码图片地址
        })
    })
    .catch(err=>{

    })

    // 轮询，查询支付状态
    // 轮询的时候一定要设置时间
    this.queryPaystatusInterval = setInterval(()=>{
        api.queryPayresult(this.order_id)
        .then(res=>{
            if(res.data.state){
                //订单支付成功,跳转到支付成功页面
                //清除定时器
                clearInterval(this.queryPaystatusInterval)
                this.$router.push({name:"paysuccess"})
            }
        })
    },200)
  },
  beforeDestroy(){
      //组件即将销毁时，清除定时器
    clearInterval(this.queryPaystatusInterval)
  }
}
</script>